package com.erp.erp_ui.email;

import com.alibaba.fastjson.JSONObject;
import com.erp.erp_entitys.Customer2Contact.Customer2ContactEntity;
import com.erp.erp_entitys.CustomerContact.CustomerContactEntity;
import com.erp.erp_entitys.CustomerContact.CustomerContactExample;
import com.erp.erp_entitys.Dictionary.DictionaryEntity;
import com.erp.erp_entitys.Email.*;
import com.erp.erp_entitys.User.UserEntity;
import com.erp.erp_entitys.warehouse.entity.AnnexEntity;
import com.erp.erp_servers.Customer.ICustomerService;
import com.erp.erp_servers.Customer2Contact.ICustomer2ContactService;
import com.erp.erp_servers.CustomerContact.ICustomerContactService;
import com.erp.erp_servers.Dictionary.IDictionary2Service;
import com.erp.erp_servers.Email.EmailService;
import com.erp.erp_servers.Email.Impl.ServerciEmailUnit;
import com.erp.erp_servers.Ftp.IFtpService;
import com.erp.erp_servers.User.IUserService;
import com.erp.erp_servers.warehouse.IAnnexService;
import com.erp.erp_ui.base.Base;
import com.erp.quertz.SpringUtil;
import com.erp.utils.R;
import com.erp.utils.ResultStatusEnum;
import com.sun.mail.imap.IMAPFolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping(value = "email")
public class EmailControl extends Base {
    private String zipPath="/data0/tem/zipDown";//    C:/Users/ceil/Desktop/temp          /data0/tem/zipDown
    @Autowired
    private  EmailService emailService;
    @Autowired
    private  IFtpService iFtpService;
    @Autowired
    private  IUserService userService;
    @Autowired
    private  ICustomerContactService customerContactService;
    @Autowired
    private  ICustomer2ContactService customer2ContactService;
    @Autowired
    private  IDictionary2Service dictionary2Service;
    @Autowired
    private  ICustomerService customerService;
    @Autowired
    private  IAnnexService iAnnexService;



    /**
     * 循环获取邮件服务器邮件并写入数据库
     * INBOX ：收件箱
     * Sent Messages ：发件箱
     * Drafts ：草稿箱
     * Deleted Messages ：删除箱
     * Junk ：垃圾箱
     */
    @RequestMapping(value = "GetEmailMore")
    public void upDateEmail() throws MessagingException {
//        long l = System.currentTimeMillis();
//        List<email_Pop3> pop3s = emailService.selectAllEmail_Pop3();
//        for (email_Pop3 pop : pop3s) {
//           try {
//               getAllemail(pop);
//           }catch (Exception e){
//
//           }
//
//        }
//        System.out.println("元数据总耗时" + (System.currentTimeMillis() - l));
        emailService.upDateEmail();
    }

    @ResponseBody
    @RequestMapping(value = "GetEmailOme")
    public R<String> upDateEmail2() {
        UserEntity user = (UserEntity) this.getBean("user");
        String re="";
        List<email_Pop3> pop3s = emailService.selectAllEmail_Pop3byUserCode(user.getCode());
        for (email_Pop3 pop : pop3s) {
           try{
            getAllemail(pop);
           }catch (Exception e){
               re+=pop.getEmail_name();
               emailService.deleteAuto(new emailAuto(pop.getPop3_id()));
           }
        }
        if(re==""){
            return R.build("success");
        }else{
            return R.build(re);
        }

    }
    //获取所有邮件
    public void getAllemail(email_Pop3 pop) throws MessagingException {
        emailService.getAllemail(pop);
    }

   //下载单个邮件附件
    @RequestMapping(value = "upLoadAdjunctOne")
    @ResponseBody
    public R<String> upLoadAdjunctOne(Integer emailID) throws Exception {
       return  emailService.upLoadAdjunctOne(emailID);

    }
    //下载单个邮件附件
    @RequestMapping(value = "upLoadAdjunctOne2")
    @ResponseBody
    public R<String> upLoadAdjunctOne2(Integer emailID) throws Exception {
        emailService.deleteContext(emailID);
        emailService.updateEmail_emailReady2(emailID);
        return  emailService.upLoadAdjunctOne(emailID);
    }
    //获取系统变量进行处置
    public static int getValue(List<DictionaryEntity> list){
        int x=0;
        for (DictionaryEntity d:list){
            if(d.getCode()!=null){
                x=Integer.parseInt(d.getName());
            }
        }
        return x;
    }
    //判断是否符合下载条件
    public boolean isTrue(){
        //当前系统使用情况
        int diskLoad =new Double(EmailUnit.diskLoad()).intValue();
        int cpuLoad = EmailUnit.cpuLoad();
        int memoryLoad = EmailUnit.memoryLoad();
        //准许下载使用情况
        IDictionary2Service dictionary2Service= SpringUtil.getBean(IDictionary2Service.class);
        int disk= getValue(dictionary2Service.getValue(6, 52));
        int cpu= getValue(dictionary2Service.getValue(6, 51));
        int memory= getValue(dictionary2Service.getValue(6, 50));
        if(diskLoad<disk&&cpuLoad<cpu&&memoryLoad<memory){
            return true;
        }else{
            return false;
        }
    }
    //下载全部邮件的附件
    @RequestMapping(value = "upLoadAdjunctMore")
    public void upLoadAdjunctMore() throws Exception {
        emailService.upLoadAdjunctMore(dictionary2Service,iFtpService);
    }

    //新增标签
    @RequestMapping(value = "insertTag")
    public void insertTag(int emailID, String tag) {
        emailService.insertTag(emailID, tag);
    }

    //删除标签
    @RequestMapping(value = "deleteTag")
    public void deleteTag(int emailID) {
        emailService.deleteTag(emailID);
    }

    //新增星标
    @RequestMapping(value = "insetStar")
    public void insetStar(int emailID) {
        emailService.insertStar(emailID);
    }

    //删除星标
    @RequestMapping(value = "deleteStar")
    public void deleteStar(int emailID) {
        emailService.deleteStar(emailID);
    }

    //新增箱子
    @RequestMapping(value = "insertBox")
    public void insertBox(String boxName, searchEmail searchEmail, int box_grade) {
        //获取到当前登录用户信息
        UserEntity user = (UserEntity) this.getBean("user");
        int searchID = emailService.insertSearch(searchEmail);
        email_box box = new email_box(boxName, user.getName(), EmailUnit.getNowSqlDate(), searchID, user.getCode(), box_grade);
        emailService.insertBox(box);
    }

    //查询所有箱子
    @RequestMapping(value = "selectBox")
    @ResponseBody
    public R<List<email_box>> selectBox() {
        UserEntity user = (UserEntity) this.getBean("user");
        String userCode=user.getCode();
        List<UserEntity> users=userService.getAllUser();
        //未创建内部联系人箱子的用户集合
        List<UserEntity> noUsers=new ArrayList<>();
        //已创建内部联系人箱子的用户集合
        List<UserEntity> yesUsers=new ArrayList<>();
        List<email_box> boxes = emailService.selectAllBox(user.getCode());
        List<email_box> userBox=new ArrayList<>();
        for(email_box box:boxes){
            if(box.getBox_grade()==0){
                userBox.add(box);
            }
        }
        for(UserEntity u:users){
            boolean isYes=false;
            for(email_box box:userBox){
                //用户箱子和用户进行对比，如果对应的code和email相等，则已存在
                if(box.getBox_creat_user().equals(u.getCode())){
                    isYes=true;
                }
            }
            if(isYes){
                yesUsers.add(u);
            }
        }

        Map<UserEntity,Integer> map = new HashMap<>();
        for (UserEntity department : users) {
            map.put(department, 1);
        }
        for (UserEntity department : yesUsers) {
            if(map.get(department)!=null)
            {
                map.put(department, 2);
                continue;
            }
            noUsers.add(department);
        }
        for(Map.Entry<UserEntity, Integer> entry:map.entrySet())
        {
            if(entry.getValue()==1)
            {
                noUsers.add(entry.getKey());
            }
    }
        if(noUsers.size()>0){
            for(UserEntity u:noUsers){
                //没有对应箱子创建箱子
                if(u.getCode().equals(userCode)==false){
                    searchEmail searchEmail=new searchEmail();
                    searchEmail.setIsAdjunct(-1);
                    searchEmail.setSenderAddresser(u.getEmail());
                    emailService.insertSearch(searchEmail);
                    email_box box = new email_box(u.getName(), u.getCode(), EmailUnit.getNowSqlDate(), searchEmail.getSearch_id(), userCode, 0);
                    emailService.insertBox(box);
                }else{
                   //有对应箱子修改箱子规则
                }
            }
            return R.build(emailService.selectAllBox(user.getCode()));
        }else{
            return R.build(boxes);
        }
    }
    //根据箱子id查询单个箱子
    @RequestMapping(value = "selectBoxById")
    @ResponseBody
    public R<email_box> selectBoxById(String box_id) {
        int i = Integer.parseInt(box_id);
        email_box box=emailService.selectBoxById(i);
        return R.build(box);
    }
    //根据规则id查询单个规则
    @RequestMapping(value = "selectSearchById")
    @ResponseBody
    public R<searchEmail> selectSearchById(String search_id) {
        int i = Integer.parseInt(search_id);
        searchEmail search=emailService.selectSearch(i);
        return R.build(search);
    }

    //查询箱子内所有邮件
    @RequestMapping(value = "custorShowEmailByPage")
    @ResponseBody
    public R<List<email_email>> custorShowEmailByPage(String code,Integer proPost) {
        ArrayList<String> emails=new ArrayList<>();
        String[] split = code.split(";");
        for(int i =0;i<split.length;i++){
            emails.add(split[i]);
        }
        List<email_email> data=emailService.selectCustorShowEmailByPage(emails);
        for(email_email e:data){
            String s=ServerciEmailUnit.resolveToEmojiFromByte(e.getSubject());
            if(proPost==1){
                s=change(s);
            }
            e.setSubject(s);
        }
        return R.build(data);
    }
    //查询箱子内所有邮件
    @RequestMapping(value = "selectBox_emailByPage")
    @ResponseBody
    public R<List<email_email>> selectBox_email(Integer box_id, Integer grade,Integer proPost) {
            List<email_email> data = emailService.selectEmailForBoxID(box_id);
        for(email_email e:data){
            String s=ServerciEmailUnit.resolveToEmojiFromByte(e.getSubject());
            if(proPost==1){
                s=change(s);
            }
            e.setSubject(s);
        }
            return R.build(data);
//        if(grade==0){//联系人箱
//            List<email_email> data = emailService.selectEmailForBoxID(box_id);
//            for(email_email e:data){
//                e.setSubject(ServerciEmailUnit.resolveToEmojiFromByte(e.getSubject()));
//            }
//            return R.build(data);
//        }else if(grade==1){//自定义箱
//            List<email_email> data = emailService.selectEmailForBoxID(box_id);
//            for(email_email e:data){
//                e.setSubject(ServerciEmailUnit.resolveToEmojiFromByte(e.getSubject()));
//            }
//            return R.build(data);
//        }else{//查询箱
//            email_box email_box = emailService.selectBoxById(box_id);
//            UserEntity user = (UserEntity) this.getBean("user");
//            List<email_Pop3> email_pop3s = emailService.selectAllEmail_Pop3byUserCode(user.getCode());
//            searchEmail searchEmail = emailService.selectSearch(email_box.getSelect_rule());
//            List<Integer> popids=new ArrayList<>();
//            for(email_Pop3 p:email_pop3s){
//                popids.add(p.getPop3_id());
//            }
//            searchEmail.setPopids(popids);
//            List<email_email> data = emailService.selectEmailByGaoji(searchEmail);
//            for(email_email e:data){
//                e.setSubject(ServerciEmailUnit.resolveToEmojiFromByte(e.getSubject()));
//            }
//            return R.build(data);
//        }
    }
    //查询箱子内所有邮件
    @RequestMapping(value = "selectBox_email1ByPage")
    @ResponseBody
    public R<List<email_email>> selectBox_email1( int search_id, String subject, String tag,String recipientName, String recipientAddress, String recDateStart, String recDateEnd,String addresser, String senderAddresser,
            String sendDateStart, String sendDateEnd,  String copyer,  String copyAddress, int isAdjunct, int email_class,  String traceDateStart, String traceDateEnd,  String approvalDateStart, String approvalDateEnd,
             String approvalPeaple, String adjunct,  int sub,@RequestParam(value = "pop3id") String pop3,@RequestParam(value = "proPost") Integer proPost) {
        List<Integer> popids=new ArrayList<>();
        String[] split = pop3.split(";");
        for(int i=0;i<split.length;i++){
            popids.add(Integer.parseInt(split[i]));
        }
        searchEmail search=new searchEmail(search_id,  subject, tag,  recipientName,  recipientAddress,  recDateStart,  recDateEnd, addresser, senderAddresser,sendDateStart,  sendDateEnd, copyer,  copyAddress, isAdjunct,  email_class,  traceDateStart,traceDateEnd, approvalDateStart, approvalDateEnd,  approvalPeaple, adjunct,  popids,  sub);

        List<email_email> data = emailService.selectEmailByGaoji(search);
        for(email_email e:data){
            String s=ServerciEmailUnit.resolveToEmojiFromByte(e.getSubject());
            if(proPost==1){
                s=change(s);
            }
            e.setSubject(s);
        }
        return R.build(data);
    }

    @RequestMapping(value = "selectSearch")
    @ResponseBody
    public R<searchEmail> selectSearch(Integer box_id, Integer grade) {
            email_box email_box = emailService.selectBoxById(box_id);
            UserEntity user = (UserEntity) this.getBean("user");
            List<email_Pop3> email_pop3s = emailService.selectAllEmail_Pop3byUserCode(user.getCode());
            searchEmail searchEmail = emailService.selectSearch(email_box.getSelect_rule());
            List<Integer> popids=new ArrayList<>();
            for(email_Pop3 p:email_pop3s){
                popids.add(p.getPop3_id());
            }
            searchEmail.setPopids(popids);
            return R.build(searchEmail);
    }
    //删除箱子及箱子内邮件
    @RequestMapping(value = "deleteBox")
    @ResponseBody
    public R<String> deleteBox(String box_id) {
        int box_id1 = Integer.parseInt(box_id);
        email_box email_box = emailService.selectBoxById(box_id1);
        String ss="删除成功";
        try {
            //还原邮件
            List<email_email> email_emails = emailService.selectEmailForBoxID(box_id1);
            List<email_email> e1=new ArrayList<>();//收件
            List<email_email> e2=new ArrayList<>();//发件
            for(email_email e:email_emails){
                if(e.getMessage_id()==-1){
                    e2.add(e);
                }else{
                    e1.add(e);
                }
            }
            if(e1.size()>0){
                emailService.ReturnEmailByBoxId(e1);//收件
            }
            if(e2.size()>0){
                emailService.ReturnEmailByBoxId1(e2);//发件
            }
            //删除箱子
            emailService.deleteBox_email(box_id1);
            emailService.deleteSearch(email_box.getSelect_rule());
            emailService.deleteBox(box_id1);
        }catch (Exception e){
            System.out.println("出错："+e);
            ss="删除失败";
        }
        return R.build(ss);

    }

    //归并操作,手动触发,返回归并失败的邮件
    @RequestMapping(value = "incloudEmail", method = RequestMethod.POST)
    @ResponseBody
    public R<String> incloudEmail(@RequestBody List<email_email> emails) {
        //判断原理：有限符合用户自建规则，再符合默认规则，如果都不符合，按照邮件发件地址新建规则
        UserEntity user = (UserEntity) this.getBean("user");
        //拆分箱子，box2为自建箱子，box1为默认箱子
        List<email_box> boxes = emailService.selectAllBox(user.getCode());
        List<boxAndSearch> boxAndSearches=new ArrayList<>();//装有所有的箱子及对应规则
        HashMap<Integer,List<email_email>> hashMap=new HashMap<>();//利用hashmap的特性来避免多层for循环及多次数据库写入
        for(email_box b2 : boxes){
            if(b2.getBox_grade()!=2){
            searchEmail search = emailService.selectSearch(b2.getSelect_rule());
            boxAndSearches.add(new boxAndSearch(b2,search));
            hashMap.put(b2.getBox_id(),new ArrayList<email_email>());
            }
        }
        //进行比对
        Set<email_email> trueEmail = new HashSet<>();
        List<email_email> changeClass= new ArrayList<>();//修改邮件归类
        for (email_email email : emails) {
            try {
                boolean isIncloud=false;
                for (boxAndSearch b : boxAndSearches) {//邮件加入用户自建箱
                    email_box box = b.getBox();
                    searchEmail searchEmail = b.getSearchEmail();
                    boolean bb = EmailUnit.compareEmail(email, searchEmail,emailService);
                    if (bb == true) {//邮件符合规则
                        hashMap.get(box.getBox_id()).add(email);
                        changeClass.add(email);
                        trueEmail.add(email);
                        isIncloud=true;
                    }
                }
                if(isIncloud==false){//进行客户箱归并
                    List<email_box> box=emailService.selectUserBoxByTwoCode1(email.getSenderAddresser());
                    if(box!=null){
                        for(int i=0;i<box.size();i++){
                            //鉴于客户箱数量过多，先进行判断是否存在相应箱子，如果没有，新增
                            if(hashMap.containsKey(box.get(i).getBox_id())==false){
                                List<email_email> es=new ArrayList<>();
                                hashMap.put(box.get(i).getBox_id(),es);
                            }
                            hashMap.get(box.get(i).getBox_id()).add(email);
                            changeClass.add(email);
                            trueEmail.add(email);
                        }

                    }
                }
            }catch (Exception e){
                System.out.println("邮件归并失败报错"+e);
            }
        }
        if(changeClass.size()>0){
            changeEmailsClass(changeClass,8);
        }
        Iterator<Map.Entry<Integer, List<email_email>>> iterator = hashMap.entrySet().iterator();
        while(iterator.hasNext()){
            Map.Entry<Integer, List<email_email>> next = iterator.next();
            Integer boxid = next.getKey();
            List<email_email> emais = next.getValue();
            for(email_email e:emais){
                List<email_box_emailid> email = emailService.selectAllEmailForBoxIsExist(e.getEmail_id());
                //如果箱子里面查不出邮件，则邮件未归并过，直接修改箱子即可,如果查询到了，则已经归并过，进行删除后修改箱子
                if(email.size()>0){
                    emailService.deleteEmailInBox(email.get(0).getEmail_id());
                }
            }
            if(emais.size()>0){
                emailService.insertBox_Email(new email_box_emailid(boxid,emais));
            }
        }
        String returnString="成功归并邮件："+trueEmail.size()+"封;未找到对应箱体邮件:"+(emails.size()-trueEmail.size())+"封";
        R<String> build = R.build(returnString);
        return build;

    }
//带条件归并
    @RequestMapping(value = "incloudMoreEmails")
    public R<String> incloudMoreEmails(@RequestParam(value = "type")Integer type){
        if(type==0){//归并已回复
            UserEntity user = (UserEntity) this.getBean("user");
            String code = user.getCode();
            List<email_Pop3> pop3s = emailService.selectAllEmail_Pop3byUserCode(code);
            List<email_email> emails=emailService.selectEmailByAnswer(pop3s);
            incloudEmail(emails);
            return incloudEmail(emails);
        }else if(type==1){//归并已读
            UserEntity user = (UserEntity) this.getBean("user");
            String code = user.getCode();
            List<email_Pop3> pop3s = emailService.selectAllEmail_Pop3byUserCode(code);
            List<email_email> emails=emailService.selectEmailByready(pop3s);
            return incloudEmail(emails);
        }else {
            return null;
        }

    }
    //新建账户操作：新增pop3账号和smtp账号
    @RequestMapping(value = "insertPopAndSmtp")
    @ResponseBody
    public R<String> insertPopAndSmtp(String name, String pass) {
        UserEntity user = (UserEntity) this.getBean("user");
        List<email_account> accounts = emailService.selectEmail_accountBycode(user.getCode());
        for(email_account ac:accounts){
            if(ac.getAccount_name()==name){
                return R.build("已存在该账号，创建失败");
            }
        }
        email_Pop3 pop3=new email_Pop3(user.getCode(),name,user.getName(),name,"imap",null,name,pass,pass,null,0,"-1",0);
        pop3.setPop_send_num("-1");
        email_smtp smtp=new email_smtp(user.getCode(),name,user.getName(),name,name,null,name,pass,pass,null,0);
        emailService.insertPop3(pop3);
        emailService.insetStmp(smtp);
        emailService.insertEmail_account(new email_account(user.getCode(),name,pop3.getPop3_id(),smtp.getSmtp_id(),0));
        return  R.build("创建成功");
    }
    //邮箱账户操作：删除账户
    @RequestMapping(value = "deleteAccount")
    @ResponseBody
    public R<String> deleteAccount(Integer accid) {
        email_account account = emailService.selectEmail_accountById(accid);
        emailService.deletePop3(account.getPop3_id());
        emailService.deleteStmp(account.getSmtp_id());
        email_account acc=new email_account();
        acc.setAccount_id(accid);
        emailService.deleteEmail_account(acc);
        return R.build("删除成功");
    }

    //修改邮箱账户状态  1可用 0不可用 2默认
    @RequestMapping(value = "changeAccountStatue")
    @ResponseBody
    public R<String> changeAccountStatue(Integer accid, Integer statues) {
        UserEntity user = (UserEntity) this.getBean("user");
        email_account account = emailService.selectEmail_accountById(accid);
        email_Pop3 pop3 = emailService.selectPOP3Bypop3_id(account.getPop3_id());
        String popLink = emailService.popLink(pop3,user);
        email_smtp email_smtp = emailService.selectStmpById(account.getSmtp_id());
        String smtpLink = emailService.smtpLink(email_smtp,user);
        if(statues==2){//默认设置
            if(popLink.equals("")&&smtpLink.equals("")){//连接均通过
                emailService.updateEmail_accountStatues();//取消默认账户
                pop3.setPop3_useStatus(statues);
                email_smtp.setSmtp_useStatus(statues);
                account.setAcccountStatue(statues);
                updatePop3(pop3);
                updateStmp(email_smtp);
                emailService.updateEmail_account(account);
                return R.build("设置默认成功");
            }
            if(!popLink.equals("")){
                return R.build(popLink);
            }
            if (!smtpLink.equals("")){
                return R.build(smtpLink);
            }
                return R.build("");
        }else if(statues==1){//启用设置
            if(popLink.equals("")&&smtpLink.equals("")){//连接均通过
                pop3.setPop3_useStatus(statues);
                email_smtp.setSmtp_useStatus(statues);
                account.setAcccountStatue(statues);
                updatePop3(pop3);
                updateStmp(email_smtp);
                emailService.updateEmail_account(account);
                return R.build("设置启用成功");
            }
            if(!popLink.equals("")){
                return R.build(popLink);
            }
            if (!smtpLink.equals("")){
                return R.build(smtpLink);
            }
                return R.build("");
        }else if(statues==0){//禁用设置
            pop3.setPop3_useStatus(statues);
            email_smtp.setSmtp_useStatus(statues);
            account.setAcccountStatue(statues);
            updatePop3(pop3);
            updateStmp(email_smtp);
            emailService.updateEmail_account(account);
            return R.build("禁用成功");
        }else{
            return R.build("");
        }
    }
    //展示账号
    @RequestMapping(value = "showAccount")
    @ResponseBody
    public R<List<email_account>> showAccount() {
        UserEntity user = (UserEntity) this.getBean("user");
        List<email_account> accounts = emailService.selectEmail_accountBycode(user.getCode());
        return R.build(accounts);

    }

    //新增pop3
    @RequestMapping(value = "insertPop3")
    public void insertPop3(@RequestBody email_Pop3 pop3) {
        emailService.insertPop3(pop3);
    }

    //根据pop3id查pop3
    @RequestMapping(value = "selectPop3ById")
    @ResponseBody
    public R<email_Pop3> selectPop3ById(Integer popid) {
        email_Pop3 pop3 = emailService.selectPOP3Bypop3_id(popid);
        return R.build(pop3);
    }

    //修改pop3
    @RequestMapping(value = "updatePop3")
    public void updatePop3(@RequestBody email_Pop3 pop3) {
        emailService.updatePop3(pop3);
    }

    //删除pop3
    @RequestMapping(value = "deletePop3")
    public void deletePop3(List<Integer> pop3ids) {
        for (Integer id : pop3ids) {
            emailService.deletePop3(id);
        }
    }

    //查看所有的pop3
    @RequestMapping(value = "selectPop3")
    @ResponseBody
    public R<List<email_Pop3>> selectPop3() {
        UserEntity user = (UserEntity) this.getBean("user");
        String code = user.getCode();
        List<email_Pop3> pop3s = emailService.selectAllEmail_Pop3byUserCode(code);
        return R.build(pop3s);
    }

    //查看所有的acc
    @GetMapping(value = "showAccByCode")
    @ResponseBody
    public R<String> showAccByCode(Integer accid) {
        UserEntity user = (UserEntity) this.getBean("user");
        String IDs="";
        if(accid==0){//accid==0
            List<email_account> accounts = emailService.selectEmail_accountBycode(user.getCode());
            for(email_account acc:accounts){
                email_Pop3 pop3 = emailService.selectPOP3Bypop3_id(acc.getPop3_id());
                email_smtp email_smtp = emailService.selectStmpById(acc.getSmtp_id());
                if(pop3.getPop3_useStatus()!=0){
                    IDs+=pop3.getPop3_id()+";";
                }
                if(email_smtp.getSmtp_useStatus()!=0){
                    IDs+=email_smtp.getSmtp_id()+";";
                }
            }
        }else {
            email_account acc= emailService.selectEmail_accountById(accid);
            email_Pop3 pop3 = emailService.selectPOP3Bypop3_id(acc.getPop3_id());
            email_smtp email_smtp = emailService.selectStmpById(acc.getSmtp_id());
            if(pop3.getPop3_useStatus()!=0){
                IDs+=pop3.getPop3_id()+";";
            }
            if(email_smtp.getSmtp_useStatus()!=0){
                IDs+=email_smtp.getSmtp_id()+";";
            }
        }
        if(IDs.equals("")){
            IDs="-1";
        }
        return R.build(IDs);
    }
    //查看所有的acc
    @GetMapping(value = "selectAcc")
    @ResponseBody
    public R<List<email_account>> selectAcc() {
        UserEntity user = (UserEntity) this.getBean("user");
        List<email_account> accounts = emailService.selectEmail_accountBycode(user.getCode());
        return R.build(accounts);
    }
    //测试pop3是否可用,成功后保存
    @RequestMapping(value = "popLinkTest",method = RequestMethod.POST)
    @ResponseBody
    public R<String> popLinkTest(@RequestBody email_Pop3 pop3)  {
        UserEntity user = (UserEntity) this.getBean("user");
        String re=emailService.popLink(pop3,user);
        return R.build(re);
    }

    //测试stmp是否可用
    @RequestMapping(value = "smtpLinkTest",method = RequestMethod.POST)
    @ResponseBody
    public R<String> smtpLinkTest(@RequestBody email_smtp smtp) {
        UserEntity user = (UserEntity) this.getBean("user");
        String re=emailService.smtpLink(smtp,user);
        return R.build(re);
    }


    //根据smtpid查smtp
    @RequestMapping(value = "selectSmtpById")
    @ResponseBody
    public R<email_smtp> selectSmtpById(Integer smtpid) {
        email_smtp smtp1 = emailService.selectStmpById(smtpid);
        return R.build(smtp1);
    }
    //新增stmp
    @RequestMapping(value = "insertStmp")
    public void insertStmp(@RequestBody email_smtp smtp) {
        emailService.insetStmp(smtp);
    }

    //修改smtp
    @RequestMapping(value = "updateStmp")
    public void updateStmp(@RequestBody email_smtp smtp) {
        emailService.updateStmp(smtp);
    }

    //查看smtp
    @RequestMapping(value = "selectSmtp")
    @ResponseBody
    public R<List<email_smtp>> selectSmtp() {
        UserEntity user = (UserEntity) this.getBean("user");
        List<email_smtp> email_smtps = emailService.selectStmp(user.getCode());
        return R.build(email_smtps);
    }
    //删除pop3 批量删除
    @RequestMapping(value = "deleteStmp")
    public void deleteStmp(List<Integer> stmpIDs) {
        for (Integer id : stmpIDs) {
            emailService.deleteStmp(id);
        }
    }
    @RequestMapping(value = "selectDimEmailAddress")
    @ResponseBody
    public R<List<String>> selectDimEmailAddress(@RequestParam(value = "name") String name) {
        String dim=name;
        List<String> add=new ArrayList<>();//张某<804422090@qq.com>
        List<UserEntity> user = userService.selectDimUser(dim);//用户信息
        List<CustomerContactEntity> ct = customerContactService.selectByDim(dim);//客户联系人
        List<Customer2ContactEntity> ct2 = customer2ContactService.selectByDim(dim);//供应商联系人
        if(user.size()>0){
            for(UserEntity u:user){
                String nam = u.getName();
                String email = u.getEmail();
                if(email.contains(";")){
                    String[] split = email.split(";");
                   for(int i=0;i<split.length;i++){
                       add.add(nam+"&lt;"+split[i]+"&gt;");
                   }
                }else{
                    add.add(nam + "&lt;" + email + "&gt;");
                }

            }
        }
        if(ct2.size()>0) {
            for (Customer2ContactEntity c : ct2) {
                String nam = c.getName();
                String email = c.getEmail();
                if(email.contains(";")){
                    String[] split = email.split(";");
                    for(int i=0;i<split.length;i++){
                        add.add(nam+"&lt;"+split[i]+"&gt;");
                    }
                }else{
                    add.add(nam + "&lt;" + email + "&gt;");
                }
            }
        }
        if(ct.size()>0) {
            for (CustomerContactEntity c : ct) {
                String nam = c.getName();
                String email = c.getEmail();
                if(email.contains(";")){
                    String[] split = email.split(";");
                    for(int i=0;i<split.length;i++){
                        add.add(nam+"&lt;"+split[i]+"&gt;");
                    }
                }else{
                    add.add(nam + "&lt;" + email + "&gt;");
                }
            }
        }

        R<List<String>> build = R.build(add);
        build.setCode(200);
        return build;
    }

    @RequestMapping(value = "selectDimBox")
    @ResponseBody
    public R<List<String>> selectDimBox(@RequestParam(value = "name") String name) {
        String dim=name;
        List<String> add=new ArrayList<>();//
        UserEntity user = (UserEntity) this.getBean("user");
        List<email_box> boxes = emailService.selectAllBox(user.getCode());
        for(email_box box:boxes){
            if(box.getBox_name().contains(dim)){
                add.add(box.getBox_name());
            }
        }
        R<List<String>> build = R.build(add);
        build.setCode(200);
        return build;
    }
    @RequestMapping(value = "getPop3ForCode")
    @ResponseBody
    public R<String> GetPop3ForCode(){
        UserEntity user = (UserEntity) this.getBean("user");
        List<email_Pop3> pop3s = emailService.selectAllEmail_Pop3byUserCode(user.getCode());
        String pop3ids=null;
        for(email_Pop3 p:pop3s){
            pop3ids+=p.getPop3_id()+";";
        }
        return R.build(pop3ids);
    }
    @RequestMapping(value = "pop3test")
    @ResponseBody
    public R<String> test(){
        UserEntity user = (UserEntity) this.getBean("user");
        List<email_Pop3> pop3s = emailService.selectAllEmail_Pop3byUserCode(user.getCode());
        String pop3ids=null;
        for(email_Pop3 p:pop3s){
            pop3ids+=p.getPop3_id()+";";
        }

        return R.build(pop3ids);
    }
    //邮件返回前端
    @RequestMapping(value = "showAllEmailByPage")
    @ResponseBody
    public R<List<email_email>> showAllEmail(@RequestParam(value="pop3s") String pop3s, @RequestParam(value="leftPage") String leftPage, @RequestParam(value="search") String search,@RequestParam(value="proPost") Integer proPost) {
        if(leftPage.equals("")){
            leftPage="收件";
        }
        if(search.equals("")){
            search=null;
        }
        try{
            List<email_email> emails = new ArrayList<>();//这里存放的是查询出来的邮件原数据
            List<Integer> pop3IDS = new ArrayList<>();
            //查询该用户所有的pop3id，根据pop3id查询邮件并做时间排序
            String[] split = pop3s.split(";");
            for (int i=0;i<split.length;i++) {
                if(split[i]!=""){
                    pop3IDS.add(Integer.parseInt(split[i]));
                }
            }
            //根据pop3id获取全部邮件并根据时间排序
            String rule1 = null;
            emailOrder order1 = new emailOrder(rule1, pop3IDS);
            emailOrder order = EmailUnit.getemailOrder(order1, leftPage);
            if(search!=null){
                order.setSelect(search);
            }
            if(pop3IDS.size()==0){
                return R.build(emails);
            }else{
            emails = emailService.selectAllEmailBypop3IDS(order);
                for(email_email e:emails){
                    String s=ServerciEmailUnit.resolveToEmojiFromByte(e.getSubject());
                    if(proPost==1){
                        s=change(s);
                    }
                    e.setSubject(s);
                }
            return R.build(emails);}
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    public String change(String path){
        String end="(";
        path=path.replace("：",":");
        boolean re=true;
        while(re){
            int q = path.indexOf("RE:");
            int w =path.indexOf("Re:");
            int e=path.indexOf("RW:");
            int r=path.indexOf("Rw:");
            int t=path.indexOf("FW:");
            int y=path.indexOf("Fw:");
            int u=path.indexOf("回复:");
            int C=path.indexOf("回复：");
            int i=path.indexOf("转发:");
            int Z=path.indexOf("回复 :");
            int O=path.indexOf("转发：");
            int X=path.indexOf("回复 ：");
            if(path.indexOf(" ")==0){
                path= path.substring(1,path.length());
            }
            else if(q==0){
                path= path.substring(3,path.length());
                end=end+"RE:";
            }else if(w==0){
                path= path.substring(3,path.length());
                end=end+"Re:";
            }
            else if(e==0){
                path= path.substring(3,path.length());
                end=end+"RW:";
            }
            else if(r==0){
                path= path.substring(3,path.length());
                end=end+"Rw:";
            }
            else if(t==0){
                path= path.substring(3,path.length());
                end=end+"FW:";
            }
            else if(y==0){
                path= path.substring(3,path.length());
                end=end+"Fw:";
            }
            else if(u==0){
                path= path.substring(3,path.length());
                end=end+"回复:";
            }
            else if(i==0){
                path= path.substring(3,path.length());
                end=end+"转发:";
            }else if(O==0){
                path= path.substring(3,path.length());
                end=end+"转发：";
            }else if(Z==0){
                path= path.substring(4,path.length());
                end=end+"回复 :";
            }
            else if(X==0){
                path= path.substring(4,path.length());
                end=end+"回复 ：";
            }
            else if(C==0){
                path= path.substring(3,path.length());
                end=end+"回复：";
            }
            else{
                re=false;
                end=end+")";
            }
        }

        if(end.equals("()")==false){
            path=path+end;
        }
        return path;
    }

    //返回审批箱邮件
    @RequestMapping(value = "showApproveEmailByPage")
    @ResponseBody
    public R<List<email_email>> showApproveEmailByPage() {
        try{
            List<email_email> emails = new ArrayList<>();//这里存放的是查询出来的邮件原数据
            UserEntity user = (UserEntity) this.getBean("user");
            String code = user.getCode();
            emails = emailService.selectApproveEmailByCode(code);
            for(email_email e:emails){
                e.setSubject(ServerciEmailUnit.resolveToEmojiFromByte(e.getSubject()));
            }
            return R.build(emails);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }
    //返回高级查询分页showGaojiEmailByPage
    @RequestMapping(value = "showGaojiEmailByPage")
    @ResponseBody
    public R<List<email_email>> showGaojiEmailByPage(@RequestParam(value="pop3s") String pop3s, @RequestParam(value="subject") String subject, @RequestParam(value="tag") String tag, @RequestParam(value="recipientName") String recipientName,
                                                     @RequestParam(value="recipientAddress") String recipientAddress, @RequestParam(value="recDate") String recDate, @RequestParam(value="addresser") String addresser,
                                                     @RequestParam(value="senderAddresser") String senderAddresser, @RequestParam(value="sendDate") String sendDate, @RequestParam(value="isAdjunct" ) String isAdjunct,
                                                     @RequestParam(value="adjunct") String adjunct, @RequestParam(value="sub") String sub,@RequestParam(value="proPost") Integer proPost) {
        try{
            List<email_email> emails = new ArrayList<>();//这里存放的是查询出来的邮件原数据
            searchEmail search = EmailUnit.getSearch(pop3s, subject, tag, recipientName, recipientAddress, recDate, addresser, senderAddresser, sendDate, isAdjunct, adjunct, sub);
            emails=emailService.selectEmailByGaoji(search);
            for(email_email e:emails){
                String s=ServerciEmailUnit.resolveToEmojiFromByte(e.getSubject());
                if(proPost==1){
                    s=change(s);
                }
                e.setSubject(s);
            }
            return R.build(emails);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }
    }

    //新建查询箱
    @RequestMapping(value = "insertSearchbox")
    @ResponseBody
    public R<String> insertSearchBox(String zdy, String boxname, String subject, String tag, String recipientName,
                                     String recipientAddress, String recDate, String addresser,
                                     String senderAddresser, String sendDate, String isAdjunct,
                                     String adjunct, String sub){
        //新建查询箱
        //首先判断是否存在另一个唯一查询箱,如果存在，删除并删除箱体内邮件，不存在，创建
        UserEntity user = (UserEntity) this.getBean("user");
        String code = user.getCode();
        int zd=Integer.parseInt(zdy);//2是查询，3是自定义
        if(zd==3){
            zd=1;
        }
        if(recDate.equals("null")){
            recDate=null;
        }
        if(sendDate.equals("null")){
            sendDate=null;
        }
        searchEmail search = EmailUnit.getSearch("", subject, tag, recipientName, recipientAddress, recDate, addresser, senderAddresser, sendDate, isAdjunct, adjunct, sub);
        emailService.insertSearch(search);//创建规则
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date());
        email_box box=new email_box(boxname,code,format,search.getSearch_id(),code,zd);
        emailService.insertBox(box);//创建箱子
        return R.build("SUCCESS");
    }
    //修改查询箱
    @RequestMapping(value = "UpdateSearchbox")
    @ResponseBody
    public void UpdateSearchbox(String search_id,String box_id,String boxname,  String subject, String tag,String recipientName,
                                String recipientAddress, String recDate,String addresser,
                                String senderAddresser,String sendDate, String isAdjunct,
                                String adjunct,String sub){
        searchEmail search = EmailUnit.getSearch("", subject, tag, recipientName, recipientAddress, recDate, addresser, senderAddresser, sendDate, isAdjunct, adjunct, sub);
        search.setSearch_id(Integer.parseInt(search_id));
        emailService.updateSearch(search);
        email_box box = emailService.selectBoxById(Integer.parseInt(box_id));
        box.setBox_name(boxname);
        emailService.updateBox(box);
    }
    //改变邮件箱子
    @RequestMapping(value = "moveEmailBox")
    @ResponseBody
    public R<String> moveEmailBox(@RequestBody List<email_email> emails, @RequestParam(value="box_id")Integer box_id) {
        //判断箱子里面有没有这个邮件，如果没有则添加
        int success=0;
        List<email_email> es=new ArrayList<>();
        for(email_email e:emails){
            List<email_box_emailid> email = emailService.selectAllEmailForBoxIsExist(e.getEmail_id());
            //如果箱子里面查不出邮件，则邮件未归并过，直接归并即可
            if(email.size()==0){
                es.add(e);
                success++;
            }else{
                //如果箱子里面查出邮件，则邮件已归并过，删除原有的进行归并
                emailService.deleteEmailInBox(e.getEmail_id());
                es.add(e);
                success++;
            }
        }
        emailService.insertBox_Email(new email_box_emailid(box_id,es));
        for(email_email e:emails){
            e.setEmail_class(8);
        }
        changeEmailClass change=new changeEmailClass(8,emails);
        emailService.updateEmailClass(change);
        return R.build("成功移动:"+success+"封邮件");
    }
    //改变邮件类型
    @RequestMapping(value = "changeEmailsClass")
    @ResponseBody
    public void changeEmailsClass(@RequestBody List<email_email> emails, @RequestParam(value="emailClass")Integer emailClass) {
        for(email_email e:emails){
            List<email_box_emailid> email = emailService.selectAllEmailForBoxIsExist( e.getEmail_id());
            //如果箱子里面查不出邮件，则邮件未归并过，直接修改箱子即可,如果查询到了，则已经归并过，进行删除后修改箱子
            if(email.size()>0){
                emailService.deleteEmailInBox(e.getEmail_id());
            }
            changeEmailClass chage=new changeEmailClass(emailClass,emails);
            emailService.updateEmailClass(chage);
        }

    }
    //查看未读邮件
    @RequestMapping(value = "selectnoRead")
    @ResponseBody
    public R<Integer> selectnoRead() {
        UserEntity user = (UserEntity) this.getBean("user");
        List<email_Pop3> pop3s = emailService.selectAllEmail_Pop3byUserCode(user.getCode());
        Integer ppnow=0;
        if(pop3s.size()>0){
           ppnow= emailService.selectNoRead(pop3s);
        }

        return R.build(ppnow);//未读邮件
    }

    //修改星标 changeXinbiao
    @RequestMapping(value = "changeXinbiao")
    @ResponseBody
    public void changeXinbiao(Integer emailID) {
        email_email email = emailService.selectEmailByEmail_id(emailID);
        if(email.getStar()==0){
            emailService.changeXinbiao1(emailID);
        }else if(email.getStar()==1){
            emailService.changeXinbiao0(emailID);
        }
    }

    @RequestMapping(value = "changeEmailsStar")
    @ResponseBody
    public void changeEmailsStar(@RequestBody List<email_email> emails, @RequestParam(value = "type") Integer type) {
        if(type==1){
            for(email_email email:emails){
                emailService.changeXinbiao1(email.getEmail_id());
            }
        }else{
            for(email_email email:emails){
                emailService.changeXinbiao0(email.getEmail_id());
            }
        }

    }
//修改已读未读changeEmailReady
    @RequestMapping(value = "changeEmailReady")
    @ResponseBody
    public void changeEmailReady(@RequestBody List<email_email> emails, @RequestParam(value = "type") Integer type) throws MessagingException {
       changeEmailReady chage=new changeEmailReady(type,emails);
       emailService.changeEmailReady(chage);
    }
    //全部设置已读
    @RequestMapping(value = "changeAllEmailReady")
    @ResponseBody
    public void changeAllEmailReady(){
        UserEntity user = (UserEntity) this.getBean("user");
        List<email_Pop3> pop3s = emailService.selectAllEmail_Pop3byUserCode(user.getCode());
        emailService.changeAllEmailReady(pop3s);
        //是否需要邮件服务器修改
    }
    //删除页面adjunct
    @RequestMapping(value = "deleteTempAdjunct")
    @ResponseBody
    public void deleteTempAdjunct(String fileName, String filePath) {
        File file=new File(filePath);
        if(file.exists()){
            file.delete();
        }
    }
    //删除标签
    @RequestMapping(value = "deleteBiaoqian")
    @ResponseBody
    public R<Tag> deleteBiaoqian(Integer emailID, Integer id) {
        email_email email = emailService.selectEmailByEmail_id(emailID);
        String tag = email.getTag();
        String[] split = tag.split(";");
        List<Tag> tags=new ArrayList();
        for(int i=0;i<split.length;i++){
            String[] split1 = split[i].split(",");
            Tag t=new Tag(Integer.parseInt(split1[0]),split1[1],split1[2]);
            if(Integer.parseInt(split1[0])!=id){
                tags.add(t);
            }
        }
        String newTag="";
        int i=1;
        for(Tag t:tags){
            newTag+=i+","+t.getColor()+","+t.getTitle()+";";
            i++;
        }
        Tag tt=new Tag(emailID,newTag);
        emailService.changeTag(tt);
        return R.build(tt);
    }
    //新增标签
    @RequestMapping(value = "addTag")
    @ResponseBody
    public R<Tag> addTag(Integer emailID, String title, String color) {
        email_email email = emailService.selectEmailByEmail_id(emailID);
        String tag = email.getTag();
        Integer s=1;
        //tag可能是null或者""
        if(tag==null){
            tag="";
        }else if(tag.equals("")){
        }else{
            String[] split = tag.split(";");
            s =Integer.parseInt(split[split.length - 1].split(",")[0])+1;
        }
        String newTag=tag+s+","+color+","+title+";";
        Tag tt=new Tag(emailID,newTag);
        emailService.changeTag(tt);
        return R.build(tt);
    }
    //
    @RequestMapping(value = "showPop3sByCode")
    @ResponseBody
    public R<String> showPop3sByCode(Integer emailID) {
        UserEntity user = (UserEntity) this.getBean("user");
        List<email_Pop3> pop3s = emailService.selectAllEmail_Pop3byUserCode(user.getCode());
        List<email_smtp> smtps = emailService.selectStmp(user.getCode());
        String pop3ids="";
        for(email_Pop3 p:pop3s){
            pop3ids+=p.getPop3_id()+";";
        }
        for(email_smtp s:smtps){
            pop3ids+=s.getSmtp_id()+";";
        }
        return R.build(pop3ids);
    }

    //单封邮件邮件返回前端 如果邮件没有下载相应附件，先下载附件再打开
    @RequestMapping(value = "showEmailbyID")
    @ResponseBody
    public R<email_email> showEmailbyID(Integer emailID,Integer isread) {
        email_email email = emailService.selectEmailByEmail_id(emailID);
        String subject = email.getSubject();
        subject=ServerciEmailUnit.resolveToEmojiFromByte(subject);
        email.setSubject(subject);
        if(isread!=null&&isread==0){
            emailService.updateReadStatue(emailID);
        }
        return R.build(email);
    }
    //单封邮件邮件返回前端 如果邮件没有下载相应附件，先下载附件再打开
    @RequestMapping(value =  "showEmailbyIDLostUser")
    @ResponseBody
    public R<email_email> showEmailbyIDLostUser(Integer emailID) {
        email_email email = emailService.selectEmailByEmail_id(emailID);
        email_Pop3 pop3 = emailService.selectPOP3Bypop3_id(email.getPop3_id());
        String subject = email.getSubject();
        subject=ServerciEmailUnit.resolveToEmojiFromByte(subject);
        email.setSubject(subject);
        try {
            String senderAddresser = email.getSenderAddresser();
            String addresser = email.getAddresser();
            if(addresser!=null&&addresser.equals("")==false){
                String s = addresser.replaceAll(",", " ").replaceAll("，", "");
                senderAddresser=s+"&lt;"+senderAddresser+"&gt;";
            }
            email.setSenderAddresser(senderAddresser);
            String recipientAddress = email.getRecipientAddress();
            String recipient="";
            String[] split = recipientAddress.split(";");
            if(split.length>0){
                for(String s:split){
                    if(s.equalsIgnoreCase(pop3.getEmail_adress())==false){
                        recipient+=s+";";
                    }else{

                    }
                }
            }
            email.setReturnRecipientAddress(recipient);
            String copyAddress = email.getCopyAddress();
            String copyAdd="";
            String[] split1 = copyAddress.split(";");
            if(split.length>0){
                for(String s:split1){
                    if(s.equalsIgnoreCase(pop3.getEmail_adress())==false){
                        copyAdd+=s+";";
                    }
                }
            }
            email.setReturnCopyAddress(copyAdd);
            String darkSendAddress = email.getDarkSendAddress();
            String darkSend="";
            String[] split2 = darkSendAddress.split(";");
            if(split.length>0){
                for(String s:split2){
                    if(s.equalsIgnoreCase(pop3.getEmail_adress())==false){
                        darkSend+=s+";";
                    }
                }
            }
            email.setReturnDarkSendAddress(darkSend);
            email.setCharset(recipientAddress+";"+copyAddress);
        }catch (Exception e){
            System.out.println("修改邮件收件人、抄送人出错");
        }
        return R.build(email);
    }

    @RequestMapping(value = "showEmailAdjunctbyID")
    @ResponseBody
    public R<List<email_adjunct>> showEmailAdjunctbyID(Integer emailID) {
        List<email_adjunct> email_adjuncts = emailService.selectAdjunctForEmail_ID(emailID);
        for(email_adjunct ad:email_adjuncts){
            if(ad.getIsText()==1){
                String textAddress = ad.getTextAddress();
                textAddress=textAddress.replaceAll("table-layout:fixed;","").replaceAll("table-layout:automatic","").replaceAll("table-layout:inherit","");
                ad.setTextAddress(ServerciEmailUnit.resolveToEmojiFromByte(textAddress));
            }
        }
        return R.build(email_adjuncts);
    }

    //发送邮件  抄送、密送  前端传送到后端的是一个message对象
    @RequestMapping(value = "sendEmail",method=RequestMethod.POST)
    @ResponseBody
    public R<String> sendEmail(@RequestBody email_message message) throws Exception {
        UserEntity user = (UserEntity) this.getBean("user");
        //延迟发送  首先判断邮件是否有定时发送，如果没有定时发送，则采取延迟发送，如果没有延迟发送，则立即发送
        SimpleDateFormat sdff = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        email_deploy deploy=null;
        Integer delaySend=0;
        try {
            deploy = emailService.selectDeploy(user.getCode());
            delaySend = deploy.getDelaySend();//分钟
        }catch (Exception e){
            System.out.println("账号设置空值异常");
        };
        Date date=null;
        if(message.getSendDate()!=""){//有定时发送
            String dingshi = message.getSendDate();
            date=sdff.parse(dingshi);
            emailService.insetSendMessage(new send_message(date, EmailUnit.obj2byte(message)));
            return R.build("已进入定时发送序列");
        }else if(delaySend!=null&&delaySend!=0){//延迟发送
            Calendar beforeTime = Calendar.getInstance();
            beforeTime.add(Calendar.MINUTE, delaySend);// 3分钟之后的时间
            Date beforeD = beforeTime.getTime();
            String time = sdff.format(beforeD);
            date = sdff.parse(time);
            emailService.insetSendMessage(new send_message(date,EmailUnit.obj2byte(message)));
            return R.build("已进入延时发送序列");
        }else {
            return sendEmailNow(message);
        }
    }

    public R<String> sendEmailNow(email_message message){
        return emailService.sendEmailNow(message);
    }
    //存草稿  前端传送到后端的是一个message对象
    @RequestMapping(value = "saveEmail", method = RequestMethod.POST)
    @ResponseBody
    public String  saveEmail(@RequestBody email_message message) throws Exception {
        //权限设置  差审批
        UserEntity user = (UserEntity) this.getBean("user");
        return emailService.saveEmail(message,user,3);
//        HashMap<String, String> aduncts = message.getAduncts();
//        Map<String, String> sendAddres = message.getSendAddres();//收件人
//        email_smtp smtp = emailService.selectStmpById(message.getStmpId());
//        String sendN="";
//        String sendA="";
//        Iterator<Map.Entry<String, String>> iterator1 = sendAddres.entrySet().iterator();
//        while (iterator1.hasNext()){
//            Map.Entry<String, String> next = iterator1.next();
//            String name = next.getKey();
//            String address = next.getValue();
//            sendN+=name+";";
//            sendA+=address+";";
//        }
//        List<String> copyAddress = message.getCopyAddress();
//        String copy="";
//        if(copyAddress.size()>0){
//            for(String cp:copyAddress){
//                copy+=cp+",";
//            }
//        }
//        List<String> darkAddress = message.getDarkAddress();
//        String dark="";
//        if(darkAddress.size()>0){
//            for(String dar:darkAddress){
//                dark+=dar+",";
//            }
//        }
//        UserEntity user = (UserEntity) this.getBean("user");
//        List<email_Pop3> pop3s = emailService.selectAllEmail_Pop3byUserCode(user.getCode());
//        //元数据存放
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        String format = sdf.format(new Date());
//        email_email email=new email_email(-1,smtp.getSmtp_server(),-1,-1,-1,-1,3,message.getSubject(),user.getCode(),smtp.getEmail_adress(),sendN,sendA,null,copy,dark,-1,user.getCode(),format,null,format,message.getCharset(),message.getIsmore(),smtp.getSmtp_id(),1,message.getPictures().size(),message.getAduncts().size(),1,null,0);
//        email.setRecipientAddress(sendA);
//        emailService.addEmail_email(email);
//        String pathName = "/email/draft/" + pop3s.get(0).getEmail_adress() + "/" + email.getEmail_id()+ "/";
//
//        //存储附件
//        if(aduncts.size()>0){
//            Iterator<Map.Entry<String, String>> iterator = aduncts.entrySet().iterator();
//            while (iterator.hasNext()){
//                Map.Entry<String, String> next = iterator.next();
//                String name = next.getKey();
//                String address = next.getValue();
//                String ftpPath= iFtpService.uploadEmailAdjunct(pathName, name, new FileInputStream(new File(address)));
//                email_adjunct adjunct=new email_adjunct(email.getEmail_id(),0,1,0,null,null,null,null,name,ftpPath,1);
//                emailService.insertEmail_adjunct(adjunct);
//                File file=new File(address);
//                if(file.exists()){
//                    file.delete();
//                }
//            }
//        }
//        //存储正文
//        email_adjunct context=new email_adjunct(email.getEmail_id(),0,0,1,null,message.getContenct(),null,null,null,null,1);
//        emailService.insertEmail_adjunct(context);

    }

    //群发邮件  需要按照时间进行分批次发送  群发没有抄送和暗送 时间间隔可设置
    @RequestMapping(value = "sendMoreEmail")
    public void sendMoreEmail(@RequestBody email_message message) throws Exception {
        email_smtp smtp = emailService.selectStmpById(message.getStmpId());
        UserEntity user = (UserEntity) this.getBean("user");
        email_deploy deploy = emailService.selectDeploy(user.getCode());
        SendEmail.sendEmail(smtp, message, emailService,deploy);
    }


    //上传附件
    @RequestMapping(value = "uploadAdjunctFile", method = RequestMethod.POST)
    @ResponseBody
    public R<List<String>> saveAdju(@RequestParam("file")MultipartFile file) {
        String property = System.getProperty("user.dir");
        UserEntity user = (UserEntity) this.getBean("user");
        String fen = System.getProperty("file.separator");
        String path = "";
        String oldFilename="";
        List<String> filename=new ArrayList<>();
        if (file != null) {
            oldFilename = file.getOriginalFilename();//获取原始文件名
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
            String format = sdf.format(new Date());
            String path1 = property + fen + "delete"+fen+user.getCode()+fen+format;
            File filePath = new File(path1);//根据路径创建文件夹
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            try {
                //写入文件
                path = path1 + fen + oldFilename;
                System.out.println("存储路径为" + path);
                file.transferTo(new File(path));
                filename.add(oldFilename);
                filename.add(path);
                return  R.build(filename);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return R.build(filename);
    }

    //从ftp下载附件到本地，再返回前端，用作回复、全部回复及转发
    // answerAdjunct
    @RequestMapping(value = "answerAdjunct")
    @ResponseBody
    public R<List<NameAndAddress>> answerAdjunct(Integer emailID) {
        List<email_adjunct> adjuncts = emailService.selectAdjunctForEmail_ID(emailID);
        List<NameAndAddress> adds=new ArrayList<>();
        //取得临时路径
//        String property = System.getProperty("user.dir");
//        String fen = System.getProperty("file.separator");
//        UserEntity user = (UserEntity) this.getBean("user");
//        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
//        String format = sdf.format(new Date());
//        String path1 = property + fen + "delete"+fen+user.getCode()+fen+format;

        for(email_adjunct ad:adjuncts){
            if(ad.getIsAdunct()==1){
                //下载到本地，并将附件名和地址保存  ftp/downloading?pathname=/email/lynn@fengqish.com/1348585552/&filename=202001-11薪资汇总表.xls
                String ss = ad.getAdjunctAddress();
                String[] split = ss.split("pathname=")[1].split("&filename=");
//                String s = ss.substring(26, ss.length());
//                String[] split = s.split("&");
//                String pathname=split[0];
//                String filename=ad.getAdjunctName();
//                String nowpath=path1 + fen;//本地临时文件保存地址
//                File file=new File(nowpath);
//                file.mkdirs();
//                iFtpService.downloadFile(pathname,filename,nowpath);
                adds.add(new NameAndAddress(ad.getAdjunctName(),split[0]+split[1]));
            }
        }
        return R.build(adds);
    }


    //转发邮件
    @RequestMapping(value = "sendForw")
    public void sendForw() throws MessagingException, IOException {
        //int email_id,String sendAddress,int smtpID
        int email_id = 63941;
        String sendAddress = "804422090@qq.com";
        int smtpID = 1;
        email_email email = emailService.selectEmailByEmail_id(email_id);
        email_Pop3 pop3 = emailService.selectPOP3Bypop3_id(email.getPop3_id());
        Store store = EmailUnit.getStore(pop3);
        Folder folder = store.getFolder("INBOX");//获取收件箱
        folder.open(Folder.READ_WRITE); // 设置对邮件帐户的访问权限
        IMAPFolder inbox = (IMAPFolder) folder;
        MimeMessage message = (MimeMessage) inbox.getMessageByUID(email.getMessage_id());
        email_smtp smtp = emailService.selectStmpById(smtpID);
        //1、连接邮件服务器的参数配置
        Properties props = new Properties();
        //设置用户的认证方式
        props.setProperty("mail.smtp.auth", "true");
        //设置传输协议
        props.setProperty("mail.transport.protocol", "smtp");
        //设置发件人的SMTP服务器地址
        props.setProperty("mail.smtp.host", smtp.getSmtp_server());
        //2、创建定义整个应用程序所需的环境信息的 Session 对象
        Session session = Session.getInstance(props);
        //设置调试信息在控制台打印出来
        session.setDebug(true);
        MimeMessage forward = new MimeMessage(session);
        forward.setSubject(email.getSubject());
        forward.setFrom(smtp.getEmail_adress());
        forward.setRecipient(Message.RecipientType.TO, new InternetAddress(sendAddress));
        forward.setSentDate(new Date());
        forward.setContent(message.getContent(), message.getContentType());
        Transport transport = session.getTransport();
        //设置发件人的账户名和密码
        transport.connect(smtp.getEmail_name(), smtp.getEmail_password());
        //发送邮件，并发送到所有收件人地址，message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
        transport.sendMessage(forward, forward.getAllRecipients());
        //5、关闭邮件连接
        transport.close();
        folder.close(false);// 关闭邮件夹对象
        store.close(); // 关闭连接对象
    }

    //转发邮件
    @RequestMapping(value = "index")
    public String index() {
        return "email";
    }

    //保存签名saveTemplate
    //ckeditor图片上传
    @RequestMapping(value ="saveTemplate")
    @ResponseBody
    public R<String> saveTemplate(Integer temid, String TemplateName, String TemplateText) {
       String index="success";
       try{
        UserEntity user = (UserEntity) this.getBean("user");
        if(temid==-1){//新增
            email_template template=new email_template(user.getCode(),TemplateName, TemplateText,0);
            emailService.insertTemplate(template);
        }else{//修改
            email_template template = emailService.selectTemplateByid(temid);
            template.setTemplate_name(TemplateName);
            template.setTemplate_text(TemplateText);
           emailService.updateTemplate(template);
        }}catch (Exception e){
           index="wrong";
       }
       return R.build(index);


    }

    //显示签名
    @RequestMapping("showTemplate")
    @ResponseBody
    public R<List<email_template>> showTemplate(@RequestParam(value = "type") Integer type) {
        UserEntity user = (UserEntity) this.getBean("user");
        List<email_template> templates = emailService.selectTemplates(user.getCode());
        if(type==1){//setting页面
            List<email_template> template=new ArrayList<>();
            for(email_template t:templates){
                if(t.getUser_code().equals(user.getCode())){
                    template.add(t);
                }
            }
            templates=template;
        }else if (type==2){//write页面
            for(email_template t:templates){
                if(t.getUser_code().equals("admin")){
                    String replace = t.getTemplate_text().replaceAll("#name#", user.getName()).replaceAll("#English_name#", user.getEnglishName()).replaceAll("#email#", user.getEmail()).replaceAll("#phone#",user.getPhone()).replaceAll("#qq#",user.getQq()).replaceAll("#telephone#",user.getTelephone()).replaceAll("#address#",user.getAddress());
                    t.setTemplate_text(replace);
                }
            }
        }


        return R.build(templates);
    }

    //设置默认签名
    @RequestMapping("setdefaultTemplate")
    @ResponseBody
    public void setdefaultTemplate(Integer tid) {
        UserEntity user = (UserEntity) this.getBean("user");
        emailService.updateTemplateNodefault(user.getCode());
        email_template template = emailService.selectTemplateByid(tid);
        template.setTemplateStatue(1);
        emailService.updateTemplate(template);
    }
    //删除签名
    @RequestMapping("deleteTemplate")
    @ResponseBody
    public R<String> deleteTemplate(Integer tid) {
        String st="删除成功";
        try{
       email_template t=new email_template();
       t.setTemplate_id(tid);
       emailService.deleteTemplate(t);}catch (Exception e){
            st="删除失败";
        }
        return R.build(st);
    }


    //ckeditor图片上传
    @RequestMapping("uploadCkEditor&responseType=json")
    @ResponseBody
    public void uploadWangEdit(HttpServletRequest request,@RequestParam("upload") MultipartFile file, HttpServletResponse response) {
        ckeditorUpload(request,file,response);
    }
    //ckeditor图片上传
    @RequestMapping("uploadCkEditor")
    @ResponseBody
    public void uploadWangEdit2(HttpServletRequest request,@RequestParam("upload") MultipartFile file, HttpServletResponse response) {
        ckeditorUpload(request,file,response);
    }
    public void ckeditorUpload(HttpServletRequest request,MultipartFile file, HttpServletResponse response){
        FileResponse fileResponse = new FileResponse();
        String tem = ServerciEmailUnit.getTem(dictionary2Service.getValue(6, 57));
        String fen = System.getProperty("file.separator");
        String fileName = UUID.randomUUID().toString();
        try {
            PrintWriter out = response.getWriter();
            if (file.isEmpty()) {
                String error = fileResponse.error(0, "文件为空");
                out.println(error);
            }
            String orgName = file.getOriginalFilename();
            String[] split = orgName.split("\\.");
            String suffix = split[1];
            //检查图片格式
            boolean imgTypeIsRight = checkImgType(suffix);
            if (!imgTypeIsRight){
                String error = fileResponse.error(0, "无效状态异常");
                out.println(error);
            }
            String ftpPath="";
            InputStream inputStream=file.getInputStream();
//            if(suffix.equals("png")){
//                inputStream = EmailUnit.getJpg(file, tem, fileName);
//            }
            String fileName1=fileName+"."+suffix;
            try {
                String pa="/emailTemp/";
                if(System.getProperty("os.name").toLowerCase().contains("win")){//测试使用，如果是windows系统
                    pa="/Desktop/tem/";
                }
                ftpPath = iFtpService.uploadEmailAdjunct(pa,fileName1, inputStream);
            } catch (IllegalStateException e) {
                String error = fileResponse.error(0, "无效状态异常");
                out.println(error);
                return;
            } catch (IOException e) {
                String error = fileResponse.error(0, "IO异常");
                out.println(error);
                return;
            }
            String url=EmailUnit.getWeb(request);
            String success = fileResponse.success(1, fileName, url+ftpPath, "");
            out.print(success);
        } catch (IOException ex){
            return;
        }
    }
    //ckEditor图片上传响应体
    public class FileResponse extends HashMap<String, Object> {
        Map<String,Object> msgMap = new HashMap<>();
        public String error(int code, String msg){
            FileResponse result = new FileResponse();
            msgMap.put("message",msg);
            result.put("uploaded",code);
            result.put("error",msgMap);
            return JSONObject.toJSON(result).toString();
        }
        public String success(int code, String fileName,String url,String msg){
            FileResponse result = new FileResponse();
            if(!StringUtils.isEmpty(msg)){
                msgMap.put("message",msg);
                result.put("error",msgMap);
            }
            result.put("uploaded",code);
            result.put("fileName",fileName);
            result.put("url",url);
            return JSONObject.toJSON(result).toString();
        }
    }
    //检查图片格式
    private boolean checkImgType(String suffix){
        if (!"jpg".equals(suffix)&&!"jpeg".equals(suffix)&&!"png".equals(suffix)&&!"gif".equals(suffix)){
            return false;
        } else {
            return true;
        }
    }

    //保存设置
    @RequestMapping(value = "savedeploy",method = RequestMethod.POST)
    @ResponseBody
    public void savedeploy(@RequestBody email_deploy deploy) {
        UserEntity user = (UserEntity) this.getBean("user");
        email_deploy userdeploy = emailService.selectDeploy(user.getCode());
        if(userdeploy!=null){
            deploy.setDeploy_user(userdeploy.getDeploy_user());
            deploy.setDeploy_id(userdeploy.getDeploy_id());
            emailService.updateDeploy(deploy);
        }else{
            deploy.setDeploy_user(user.getCode());
            emailService.inserteDeploy(deploy);
        }
    }
    //返回设置
    @RequestMapping(value = "showdeploy")
    @ResponseBody
    public R<email_deploy> showdeploy() {
        UserEntity user = (UserEntity) this.getBean("user");
        email_deploy deploy = emailService.selectDeploy(user.getCode());
        if(deploy!=null){
            return R.build(deploy);
        }else {
            return R.build(new email_deploy());
        }

    }



    @RequestMapping(value = "showEmailRules")
    @ResponseBody
    public R<List<EmailRules>> showEmailRules() {
        UserEntity user = (UserEntity) this.getBean("user");
        List<EmailRules> rules = emailService.selectEmailRulesBycode(user.getCode());
        return R.build(rules);
    }

    @RequestMapping(value = "deleteEmailRules")
    @ResponseBody
    public R<String> deleteEmailRules(Integer rid) {
        String index="success";
        try{
       emailService.deleteEmailRules(rid);}
        catch (Exception e){
            index="wrong";
        }
        return R.build(index);
    }

    @PostMapping(value = "saveEmailRules")
    @ResponseBody
    public R<String> saveEmailRules(@RequestBody EmailRules emailRules) {
        String index="success";
        UserEntity user = (UserEntity) this.getBean("user");
        emailRules.setUser_code(user.getCode());
        try{
            if(emailRules.getRule_id()!=-1){
                emailService.updateEmailRules(emailRules);
            }else{
                emailService.insertEmailRules(emailRules);}
            }

        catch (Exception e){
            index="wrong";
        }
        return R.build(index);
    }

    //返回首页的统计数据
    @GetMapping(value = "getNowEmail")
    @ResponseBody
    public R<String> getNowEmail() {
        UserEntity user = (UserEntity) this.getBean("user");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(new Date());
        List<email_Pop3> pop3s = emailService.selectAllEmail_Pop3byUserCode(user.getCode());
        List<email_smtp> smtps = emailService.selectStmp(user.getCode());
        Integer pnow=0;//今日收件
        Integer ppnow=0;//今日收未读邮件
        if(pop3s.size()==0){
            pnow=0;
            ppnow=0;
        }else{
            email_nowEmail pn=new email_nowEmail();//今日收件
            pn.setPop3s(pop3s);
            pn.setNowDay(format);
            pnow = emailService.selectNowEmail(pn);
            email_nowEmail pnn=new email_nowEmail();//今日未读
            pnn.setPop3s(pop3s);
            pnn.setNowDay(format);
            pnn.setReadStatue("1");
            ppnow = emailService.selectNowEmail(pnn);
        }
        Integer snow=0;
        if(smtps.size()==0){
            snow=0;
        }else {
            email_nowEmail sn = new email_nowEmail();//今日发件
            sn.setSmtps(smtps);
            sn.setNowDay(format);
            snow = emailService.selectNowEmail(sn);
        }
        return R.build(pnow+";"+snow+";"+ppnow);//"今日收件："+pnow+";今日发件："+snow+";今日未读邮件+"+ppnow
    }

    /*
     * 查询项目路径
     * */
    @GetMapping(value = "selectWeb")
    @ResponseBody
    public R<String> selectTariffRate(HttpServletRequest request){
        String basePath =EmailUnit.getWeb(request);
        return R.build(basePath);
    }

    /**
     * 图片输入到页面，用于展示
     *      *   在html中直接在img标签的src属性值为controller的请求地址即可。
     * @param pathname ftp上的路径
     * @param filename  ftp上的文件名
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "downloadimg")
    @ResponseBody
    public void downloadimg(String pathname,String filename,HttpServletResponse response) throws Exception {
        // String pathname="/ftp";
        // String filename="大数据面试总结.png";
        iFtpService.download(pathname, filename, response);
    }
    @RequestMapping(value = "cutAcc")
    @ResponseBody
    public R<String> cutAcc(String code) {
        List<email_Pop3> email_pop3s = emailService.selectAllEmail_Pop3byUserCode(code);
        String IDs="";
        for(email_Pop3 pop3:email_pop3s){
            if(pop3.getPop3_useStatus()!=0){
                IDs+=pop3.getPop3_id()+";";
            }
        }
        return R.build(IDs);

    }

    @RequestMapping(value = "selectCustomBox")
    @ResponseBody
    public R<String> selectCustomBox(String customsearchs2) {  //参数样式为  张某<rkb001>
        String[] split = customsearchs2.split(",");
        return R.build("");

    }
    @RequestMapping(value = "getUserBox_id")
    @ResponseBody
    public R<email_box> getUserBox_id(String code) {
        try {
            UserEntity user = (UserEntity) this.getBean("user");
            email_box box=emailService.selectUserBoxByTwoCode(user.getCode(),code);
            return R.build(box);
        }catch (Exception e){
            return  null;
        }
    }
    @RequestMapping(value = "getCustorBox_id")
    @ResponseBody
    public R<email_box> getCustorBox_id(String email) {
        try {
            email_box box=emailService.selectUserBoxByTwoCode(email);
            return R.build(box);
        }catch (Exception e){
            return  null;
        }
    }
    @RequestMapping(value = "deleteMuchEmail")
    @ResponseBody
    public R<String> deleteMuchEmail(){
        String re="删除成功";
        try {
            emailService.deleteMuchEmail();
        }catch (Exception e){
            re="删除失败";
        }
        return R.build(re);

    }
    @RequestMapping(value = "getCustomerscontact")
    @ResponseBody
    public R<String> getCustomerscontact(@RequestBody List<CustomerContactEntity> CustomerContactEntitys,@RequestParam(value = "company") String company,@RequestParam(value = "email") String email){
        try {
            CustomerContactExample example=new CustomerContactExample();
            CustomerContactExample.Criteria criteria = example.createCriteria();
            String[] companys=company.split(",");
            List<String> list=new ArrayList<>();
            for(String cs:companys){
                list.add(cs);
            }
            criteria.andCompanyIn(list);
            List<CustomerContactEntity> customerContactEntities = customerContactService.selectByExample(example);//总的
            HashMap<String,CustomerContactEntity> hash=new HashMap<>();
            for(CustomerContactEntity c:customerContactEntities){
                hash.put(c.getEmail(),c);
            }
            for(CustomerContactEntity c:CustomerContactEntitys){
                hash.remove(c.getEmail());
            }
            String re="";
            Iterator<Map.Entry<String, CustomerContactEntity>> iterator = hash.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry<String, CustomerContactEntity> next = iterator.next();
                re+=next.getKey()+",";
            }
            if(email!=""&&email!=null&&email!=","){
                re+=email;
            }
            return R.build(re);
        }catch (Exception e){
            e.printStackTrace();
            return R.buildError(ResultStatusEnum.ERROR);
        }

    }
    @RequestMapping(value = "selectEmailReadNum")
    @ResponseBody
    public R<List<String>> selectEmailReadNum(@RequestParam(value="pop3s") String pop3s){
        List<Integer> pop3IDS = new ArrayList<>();
        //查询该用户所有的pop3id，根据pop3id查询邮件并做时间排序
        String[] split = pop3s.split(";");
        for (int i=0;i<split.length;i++) {
            if(split[i]!=""){
                pop3IDS.add(Integer.parseInt(split[i]));
            }
        }
        if(pop3IDS.size()>0){
            List<emailReadNum> emailReadNums = emailService.selectEmailReadNum(pop3IDS);
            List<String> re=new ArrayList<>();
            //收件箱
            re.add("("+emailReadNums.get(4).getNum()+"/"+emailReadNums.get(3).getNum()+")");
            //星标箱
            re.add("("+emailReadNums.get(14).getNum()+"/"+emailReadNums.get(13).getNum()+")");
            //未读箱
            re.add("("+emailReadNums.get(1).getNum()+"/"+emailReadNums.get(1).getNum()+")");
            //草稿箱
            re.add("(0"+"/"+emailReadNums.get(5).getNum()+")");
            //待发箱
            re.add("(0"+"/"+emailReadNums.get(6).getNum()+")");
            //群发箱
            re.add("(0"+"/"+emailReadNums.get(2).getNum()+")");
            //已发箱
            re.add("(0"+"/"+emailReadNums.get(7).getNum()+")");
            //系统已发箱
            re.add("(0"+"/"+emailReadNums.get(10).getNum()+")");
            //垃圾箱
            re.add("("+emailReadNums.get(9).getNum()+"/"+emailReadNums.get(8).getNum()+")");
            //已归并箱
            re.add("("+emailReadNums.get(15).getNum()+"/"+emailReadNums.get(16).getNum()+")");
            //回收箱
            re.add("("+emailReadNums.get(12).getNum()+"/"+emailReadNums.get(11).getNum()+")");
            return R.build(re);
        }else{
            return null;
        }
    }
    /*
    * 转发，分发
    * */
    @RequestMapping(value = "emailForward")
    @ResponseBody
    public R<String> emailForward(@RequestBody emailForward forward){
        String re="转发、分发成功";
        try{
        UserEntity user = (UserEntity) this.getBean("user");
        String code = forward.getCode();
        //获取到所有需要转发分发的popid
        List<Integer> forwardid=new ArrayList<>();
        if(code!=""&&code!=null){
            String[] split = code.split(",");
            for(int i=0;i<split.length;i++){
                List<email_Pop3> pop3s = emailService.selectAllEmail_Pop3byUserCode(split[i]);
                if(pop3s.size()>0){
                    forwardid.add(pop3s.get(0).getPop3_id());
                }
            }
        }
        //对邮件进行处理，去id，加意见等操作
        List<email_email> emails = forward.getEmails();
        String idea = forward.getIdea();
        //1,#ff005d,转发意见，请查看;2,#2808f2,分发意见，请查看;
        for(email_email email:emails){
            String tag = email.getTag();
            Integer s=1;
            //tag可能是null或者""
            if(tag==null){
                tag="";
            }else if(tag.equals("")){
            }else{
                String[] split = tag.split(";");
                s =Integer.parseInt(split[split.length - 1].split(",")[0])+1;
            }
            email.setParent_id(email.getEmail_id());
            String newTag=tag+s+","+"#ff005d"+","+user.getName()+"转发:"+idea+";";
            email.setTag(newTag);
            List<email_adjunct> adjuncts1 = emailService.selectAdjunctForEmail_ID(email.getEmail_id());
            email.setAdjunctList(adjuncts1);
        }
        //进行转发和分发
        for(Integer pop3_id:forwardid){
            for(email_email email:emails){
                //创建邮件
                email.setPop3_id(pop3_id);
                email.setEmail_class(2);
                email.setRecDate(EmailUnit.getNowSqlDate());
                email.setCreateDate(EmailUnit.getNowSqlDate());
                email.setPop3_id(pop3_id);
                email.setReadStatue(1);
                email.setMessage_id(-2);
                emailService.addEmail_email(email);
                //创建附件
                List<email_adjunct> adjunctList = email.getAdjunctList();
                for(email_adjunct ad:adjunctList){
                    ad.setEmail_id(email.getEmail_id());
                    emailService.insertEmail_adjunct(ad);
                }
            }
        }}catch (Exception e){
            re="转发、分发失败";
        }
        return R.build(re);
    }


    //按照指定时间节点收件
    @RequestMapping(value = "SearchTerm")
    @ResponseBody
    public R<String> SearchTerm(Integer pop3_id, String start, String end, Integer high,Integer type) {
        //type=1  已发送  type=0  收件箱
        Date startTime = null;
        Date endTime = null;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            startTime = format.parse(start);
            endTime = format.parse(end);
        } catch (Exception e) {
            System.out.println(e);
        }
      return R.build(emailService.SearchTerm(pop3_id,startTime,endTime,high,type));
    }
    @RequestMapping(value = "zipDown")
    @ResponseBody
    public R<ArrayList<String>> zipDown(@RequestParam("email_id") Integer email_id, HttpServletResponse response, HttpServletRequest request) throws IOException {
        List<email_adjunct> adjuncts = emailService.selectAdjunctForEmail_ID(email_id);
        String nowDate=EmailUnit.getRandomFileName();
        String outPath=zipPath+"/"+nowDate;
        File file=new File(outPath);
        if(file.exists()==false){
            file.mkdirs();
        }
        for(email_adjunct a:adjuncts){
            if(a.getIsAdunct()==1){
                String fileName = a.getAdjunctName();
                //  ftp/downloadimg?pathname=C:/Users/ceil/email/nana.wang@fengqish.com/1634962321/&filename=2021120221532213557
                String adjunctAddress = a.getAdjunctAddress();
                String[] split = adjunctAddress.split("pathname=")[1].split("&filename=");
                String path=  split[0]+split[1];
                EmailUnit.copyFileUsingFileStreams(new File(path),new File(outPath+"/"+fileName));
            }
        }
        /**
         * 压缩文件
         *
         * @param sourceFilePath 源文件路径
         * @param zipFilePath    压缩后文件存储路径
         * @param zipFilename    压缩文件名
         */
        zipUnit.compressToZip(outPath,zipPath,nowDate+".zip");
        ArrayList<String> arrayList=new ArrayList();
        arrayList.add(zipPath);
        arrayList.add(nowDate+".zip");
        return R.build(arrayList);
    }

    //遍历所有的文件，找到其中重复的。保存下来
    @RequestMapping(value = "test1")
    public void test2() throws IOException {
        //第一步，获取到所有的文件名和出现次数
        List<AnnexEntity> fileNames= emailService.selectAllFileNmae();
        HashMap<String,Integer> fileMap=new HashMap<>();
        for (AnnexEntity a:fileNames){
            if(fileMap.containsKey(a.getFileName())){
               fileMap.put(a.getFileName(),fileMap.get(a.getFileName())+1);
            }
           else{
               fileMap.put(a.getFileName(),1);
            }
        }
        int i=0;
        //第二部。遍历所有的文件夹，将上诉文件存储到另一个文件夹中
        folderMethod2("E:\\共享文件",fileMap,i);
        System.out.println("结束");
    }
    //遍历所有的文件，找到其中重复的。保存下来
    public static void folderMethod2(String path, HashMap<String,Integer> fileMap,int i) throws IOException {
        File file = new File(path);
        if (file.exists()) {
            File[] files = file.listFiles();
            if (null != files) {
                for (File file2 : files) {
                    if (file2.isDirectory()) {
                        folderMethod2(file2.getAbsolutePath(),  fileMap,i);
                    } else {
                        try {
                            if(fileMap.containsKey(file2.getName())&&new File("E:\\丢失文件\\"+file2.getName()).exists()==false){
                                copyFile(file2.getAbsoluteFile().toString(),"E:\\丢失文件\\"+file2.getName());
                            }
                        }catch (Exception e){
                            System.out.println(e);
                        }


                    }
                }
            }
        } else {
            System.out.println("文件不存在!");
        }
    }
    //遍历所有的文件，找到其中重复的。保存下来
    public static void copyFile(String oldPath, String newPath) throws IOException {
            File oldFile = new File(oldPath);
            File file = new File(newPath);
            FileInputStream in = new FileInputStream(oldFile);
            FileOutputStream out = new FileOutputStream(file);
            byte[] buffer = new byte[2097152];
            int readByte = 0;
            while ((readByte = in.read(buffer)) != -1) {
                out.write(buffer, 0, readByte);
            }
            in.close();
            out.close();

    }
    //建立文件夹，并将文件进行保存
    @RequestMapping(value = "test2")
    public void test3() throws IOException {
        //第一步，获取到所有的文件名和文件路径
        List<AnnexEntity> fileNames= emailService.selectAllFileNmae();
        //第二部，获取当前的所有文件名
        File file = new File("/opt/test/丢失文件");
        File[] files = file.listFiles();
        HashMap<String,File> fileMap=new HashMap<>();
        for (File file2 : files) {//
            fileMap.put(file2.getName(),file2);
        }
        //遍历所有的附件，将文件保存至修改后的文件路径，如果成功，修改数据库
        for(AnnexEntity a:fileNames){
            String filePath = a.getFilePath();//  E:/AllPath/upload/WLCCB01/RKB031/warehouse/transfer/1618552441754.pdf
            String fileName = a.getFileName();
            //如果附件存在，则创建改路径，并保存
            if(fileMap.containsKey(fileName)){
                String s = "/data0"+filePath.substring(2,filePath.length());
//                String s = "E:\\更正测试"+filePath.substring(2,filePath.length());
                File f = new File(s);
                File f1=new File(f.getParent());
                if(!f1.exists()){
                    f1.mkdirs();
                }
                copyFile(fileMap.get(fileName).getAbsoluteFile().toString(),s);
                if(new File(s).length()>0){//文件写入成功，修改数据库
                    a.setFilePath(s);
                    iAnnexService.update(a);
                }
            }

        }
    }

    //建立文件夹，并将文件进行保存
    private Integer auto=0;
    @RequestMapping(value = "test3")
    public void test4() throws IOException {
        if(auto==0){
            auto=1;
            while(true){
                System.out.println("*****************启动*******************");
                emailService.upDateEmail();
                System.out.println("*****************结束*******************");
            }
        }
    }
}

